import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

class IntCmp implements Comparator<Integer> {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

public class Test {
    //最小K个数
    //设计一个算法，找出数组中最小的k个数。以任意顺序返回这k个数均可。

    public static int[] smallestK(int[] arr, int k) {
        int[] temp = new int[k];
        if (k == 0) {
            return temp;
        }
        PriorityQueue<Integer> p = new PriorityQueue<>(new IntCmp());
        //1.把前K个元素放进堆中
        for (int i = 0; i < k; i++) {
            p.offer(arr[i]);
        }
        //2.遍历剩下n-k个元素
        for (int i = k; i < arr.length; i++) {
            int val = p.peek();
            if (val > arr[i]) {
                p.poll();
                p.offer(arr[i]);
            }
        }
        for (int i = 0; i < k; i++) {
            temp[i] = p.poll();
        }
        return temp;
    }

    public static int[] smallestK1(int[] arr, int k) {
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        for (int i = 0; i < arr.length; i++) {
            priorityQueue.offer(arr[i]);
        }
        int[] temp = new int[k];
        for (int i = 0; i < k; i++) {
            int value = priorityQueue.poll();
            temp[i] = value;
        }
        return temp;
    }

    public static void main1(String[] args) {
        int[] arr = {27, 15, 19, 18, 28, 34, 65, 49, 25, 37};
        int[] arr1 = smallestK(arr, 3);
        System.out.println(Arrays.toString(arr1));
    }

    public static void main2(String[] args) {
        //堆模拟优先级队列
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        priorityQueue.offer(10);
        priorityQueue.offer(5);
        priorityQueue.offer(25);
        System.out.println(priorityQueue.poll());//5
        System.out.println(priorityQueue.poll());//10
    }

    public static void main(String[] args) {
        //创建大根堆
        int[] array = {27, 15, 19, 18, 28, 34, 65, 49, 25, 37};
        TestHeap testHeap = new TestHeap();
        testHeap.inti(array);
        testHeap.createHeap();
        testHeap.poll();
    }
}
